package com.leff.cards.request;

import java.util.Date;

import com.leff.cards.Dictionary;
import com.leff.cards.StoreWrapper;
import com.leff.cards.entity.Configuration;
import com.leff.cards.entity.User;


public class Login extends Request {
	
	public Login(Dictionary dict) {
		super(dict);
	}

	public RequestResult doLogin() {
		
		RequestResult result = this.verifyRequiredParameters(Parameter.FB_ID, Parameter.NAME);
		if(!result.isSuccessful()) {
			return result;
		}
		
		String idStr = (String)mDictionary.get(Parameter.FB_ID);
		long id = Long.parseLong(idStr);
		String name = (String)mDictionary.get(Parameter.NAME);
		
		User U = StoreWrapper.getOrCreateUserByFbId(id, name);
		
		U.setLastLogin(new Date());
		StoreWrapper.store(U);
		
		String versionStr = (String)mDictionary.get(Parameter.VERSION);
		boolean upgrade = false;
		if(versionStr != null) {
			int version = Integer.parseInt(versionStr);
			
			Configuration config = StoreWrapper.getConfiguration();
			upgrade = config.checkVersion(version);
			
			if(U.getVersion() != version) {
				U.setVersion(version);
				StoreWrapper.store(U);
			}
		}
		
		Dictionary data = new Dictionary();
		data.put(Parameter.ID, U.getId());
		data.put(Parameter.FB_ID, U.getFbId());
		data.put(Parameter.NAME, U.getDisplayName());
		data.put(Parameter.UPGRADE, upgrade);
		
		result.res = data;
		
		return result;
	}
}
